* Create time series of gun-related evening news coverage.

clear all
set more off


use "in-data/nonfam_shootings.dta", clear
collapse (sum) fatalities victims, by(date) fast
tempfile shootings
save `shootings'


use "out-data/shooting_news.dta", clear
merge 1:1 date using `shootings', assert(1 3) nogen
qui compress
tsset date, daily

quietly {
    replace fatalities = 0 if mi(fatalities)
    replace victims = 0 if mi(victims)
}

gen float logdur = log(1 + duration), after(duration)
gen byte dow = dow(date)
gen int year = year(date)

// fatality groups
recode fatalities (0 = 0) (4/5 = 1) (6/9 = 2) (10/10000 = 3), gen(fgrp)
cap la drop fgrp
la def fgrp 0 "0" 1 "4-5" 2 "6-9" 3 "10+"
la val fgrp fgrp

// calculate time relative to shooting event
tempvar hadfatal
gen byte since_shooting = .
gen byte to_shooting = .

forvalues lag=0/16 {
    gen byte `hadfatal' = L`lag'.fatalities > 0 if !mi(L`lag'.fatalities)
    replace since_shooting = min(since_shooting, `lag') if `hadfatal' == 1
    drop `hadfatal'
}

forvalues lead=0/16 {
    gen byte `hadfatal' = F`lead'.fatalities > 0 if !mi(F`lead'.fatalities)
    replace to_shooting = min(to_shooting, `lead') if `hadfatal' == 1
    drop `hadfatal'
}

gen byte time = max(since_shooting, -1 * to_shooting), before(dow)
drop since_shooting to_shooting

// fatality group of shooting referred to by time variable
gen byte tfgrp = fgrp[_n - time]
la val tfgrp fgrp
// fatality count of shooting referred to by time variable
gen byte tfat = fatalities[_n - time]

la var date "Date"
la var duration "News coverage in seconds"
la var logdur "Log(1 + news coverage)"
la var fatalities "Fatalities"
la var victims "Victims"
la var time "Days relative to shooting"
la var dow "Day of week"
la var year "Calendar year"
la var fgrp "Fatality group"
la var tfgrp "Fatality group of nearby shooting"

qui compress
la data "Gun-related news coverage and mass shootings"
save "out-data/gun_news.dta", replace
exit
